<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="机构" prop="institutionId">
        <el-select v-model="queryParams.institutionId" filterable placeholder="请选择机构" clearable size="small">
          <el-option
            v-for="dept in deptList"
            :key="dept.institutionId"
            :label="dept.institutionName"
            :value="dept.institutionId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="监控名称" prop="cameraName">
        <el-input
          v-model="queryParams.cameraName"
          placeholder="请输入视频监控名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['tongban:camera:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tongban:camera:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tongban:camera:remove']"
        >删除</el-button>
      </el-col>
<!--    <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['tongban:camera:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cameraList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--<el-table-column label="视频监控id" align="center" prop="cameraId" />-->
      <el-table-column label="机构名称" align="center" prop="institutionName" />
      <el-table-column label="班级名称" align="center" prop="className" />
      <el-table-column label="监控名称" align="center" prop="cameraName" />
      <el-table-column label="M3U8地址" align="center" prop="cameraRtmp" />
      <el-table-column label="RTMP地址" align="center" prop="cameraHttp" />
<!--      <el-table-column label="设备生产厂家" align="center" prop="cameraManufacturer" />
      <el-table-column label="设备品牌" align="center" prop="cameraBrand" />
      <el-table-column label="设备型号" align="center" prop="cameraModel" />-->
      <!--<el-table-column label="监控状态" align="center" prop="status" :formatter="statusFormat" />-->
<!--      <el-table-column label="拉流" align="center" prop="pullStream" />-->
      <el-table-column label="推流地址" align="center" prop="pushStream" />
      <el-table-column label="工控机IP" align="center" prop="localIp" />
      <el-table-column label="失效时间" align="center" prop="loseTime" />
      <!--<el-table-column label="缩略图id:对应sys_file表中的file_id" align="center" prop="cameraHead" />-->
      <!--<el-table-column label="在线状态:对应sys_dictionary表中的IsNot类型" align="center" prop="onlineStatus" :formatter="onlineStatusFormat" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['tongban:camera:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['tongban:camera:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleView(scope.row)"
          >预览</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleCreatePush(scope.row)"
          >重新生成推流地址</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加视频监控对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="机构" prop="institutionId" v-if="edit">
          <el-select v-model="form.institutionId" filterable placeholder="请选择机构" clearable size="small" @change="selectClass">
            <el-option
              v-for="dept in deptList"
              :key="dept.institutionId"
              :label="dept.institutionName"
              :value="dept.institutionId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="classId" v-if="edit">
          <el-select v-model="form.classId" placeholder="请选择班级" clearable size="small">
            <el-option
              v-for="dept in classList"
              :key="dept.classId"
              :label="dept.className"
              :value="dept.classId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="监控名称" prop="cameraName">
          <el-input v-model="form.cameraName" placeholder="请输入视频监控名称" />
        </el-form-item>
        <el-form-item label="工控机IP" prop="localIp">
          <el-input v-model="form.localIp" placeholder="请输入工控机IP地址名称" />
        </el-form-item>
        <el-form-item label="失效时间" prop="loseTime" v-if="edit">
          <el-date-picker
            clearable size="small"
            v-model="form.loseTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择失效时间"
            default-time="12:00:00">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加视频监控对话框 -->
    <el-dialog :title="title" :visible.sync="view" width="500px" append-to-body>
      <div v-html="content"></div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="download">下载</el-button>
        <el-button @click="cannelView">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="title" :visible.sync="createPush" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="失效时间" prop="loseTime">
          <el-date-picker
            clearable size="small"
            v-model="form.loseTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择失效时间"
            default-time="12:00:00">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="createPushSubmit">确定</el-button>
        <el-button @click="createPushCannelView">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listCamera, getCamera, delCamera, addCamera, updateCamera, exportCamera, againCreateUrl } from "@/api/tongban/camera";
import { listInstitutionData } from "@/api/tongban/institution";
import { listInstitutionClass } from "@/api/tongban/class";

export default {
  name: "Camera",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      m3u8 : null,
      pushUrl: null,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      content: null,
      // 总条数
      total: 0,
      // 视频监控表格数据
      cameraList: [],
      deptList: [],
      classList: [],
      edit:false,
      view:false,
      createPush: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 视频监控状态:对应sys_dictionary表Status类型字典
      statusOptions: [],
      // 在线状态:对应sys_dictionary表中的IsNot类型字典
      onlineStatusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        institutionId: null,
        cameraName: null,
        cameraRtmp: null,
        cameraHttp: null,
        cameraManufacturer: null,
        cameraBrand: null,
        cameraModel: null,
        status: null,
        loseTime: null,
        pullStream: null,
        pushStream: null,
        cameraHead: null,
        onlineStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        institutionId: [
          { required: true, message: "机构id不能为空", trigger: "blur" }
        ],
        cameraName: [
          { required: true, message: "视频监控名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("user_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("applets_sys_yes_no").then(response => {
      this.onlineStatusOptions = response.data;
    });
    listInstitutionData().then(res => {
      this.deptList = res.data;
    })
  },
  methods: {
    /** 查询视频监控列表 */
    getList() {
      this.loading = true;
      listCamera(this.queryParams).then(response => {
        this.cameraList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleView(row){//预览
      console.log(row)
      this.view = true;
      let m3u8 = `"${row.cameraRtmp}"`;
      let pushUrl = `"${row.pushStream}"`;
      let ip = row.localIp;
      let temp = "[relay1]" +
        "<br>name=123" +
        "<br>pullurl=rtsp://" + ip +"/stream1" +
        "<br>pushplayurl=" + m3u8 +
        "<br>pushurl=" + pushUrl +
        "<br>pushmute=true" +
        "<br>recordpath=record";
      this.content = temp;
    },
    cannelView(){//预览取消
      this.view = false;
    },
    createPushCannelView(){
      this.createPush = false;
    },
    download(){//下载
      let temp = this.content.replaceAll("<br>","\n");
      this.downloadTxt("relayconfig.ini", temp);
    },
    downloadTxt(filename, text) {
      let pom = document.createElement("a");
      pom.setAttribute(
        "href",
        "data:text/plain;charset=utf-8," + encodeURIComponent(text)
      );
      pom.setAttribute("download", filename);
      if (document.createEvent) {
        var event = document.createEvent("MouseEvents");
        event.initEvent("click", true, true);
        pom.dispatchEvent(event);
      } else {
        pom.click();
      }
    },
    // 视频监控状态:对应sys_dictionary表Status类型字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    selectClass(id){
      listInstitutionClass(id).then(res => {
        this.classList = res.data;
        console.log(id);
        //this.form.classId = this.classList[0];
      })
    },
    handleCreatePush(row){
      getCamera(row.cameraId).then(response => {
        this.form = response.data;
        this.createPush = true;
      });
/*      againCreateUrl(row.cameraId,this.form.loseTime);
      this.getList();*/
    },
    createPushSubmit(){
      againCreateUrl(this.form.cameraId, this.form.loseTime).then(res=>{
        this.createPush = false;
        this.getList();
      });
    },
    // 在线状态:对应sys_dictionary表中的IsNot类型字典翻译
    onlineStatusFormat(row, column) {
      return this.selectDictLabel(this.onlineStatusOptions, row.onlineStatus);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        cameraId: null,
        institutionId: null,
        cameraName: null,
        cameraRtmp: null,
        cameraHttp: null,
        cameraManufacturer: null,
        cameraBrand: null,
        cameraModel: null,
        status: 0,
        loseTime: null,
        pullStream: null,
        pushStream: null,
        cameraHead: null,
        onlineStatus: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.cameraId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.edit = true;
      this.title = "添加视频监控";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const cameraId = row.cameraId || this.ids
      this.edit = false;
      getCamera(cameraId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改视频监控";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.cameraId != null) {
            updateCamera(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCamera(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const cameraIds = row.cameraId || this.ids;
      this.$confirm('是否确认删除视频监控编号为"' + cameraIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCamera(cameraIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      console.log(queryParams)
      // this.$confirm('是否确认导出所有视频监控数据项?', "警告", {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     type: "warning"
      //   }).then(function() {
      //     return exportCamera(queryParams);
      //   }).then(response => {
      //     this.download(response.msg);
      //   })
    }
  }
};
</script>
